<template>
  <el-card header="新增风险预警">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      class="demo-ruleForm"
      status-icon
      label-width="80"
    >
      <el-row :gutter="40" style="width: 100%; margin: 0">
        <el-col :span="10">
          <el-form-item label="来源" prop="source">
            <el-radio-group v-model="form.source">
              <!--<el-radio label="0" size="large">智能抽查</el-radio>-->
              <!--<el-radio label="1" size="large">抽查实施</el-radio>-->
              <!--<el-radio label="2" size="large">检查实施</el-radio>-->
              <!--<el-radio label="3" size="large">其他</el-radio>-->
              <el-radio label="1" size="large">数据比对</el-radio>
              <el-radio label="2" size="large">年度检查</el-radio>
              <el-radio label="3" size="large">抽查检查</el-radio>
              <el-radio label="4" size="large">审计巡视巡查</el-radio>
              <el-radio label="5" size="large">网络舆情</el-radio>
              <el-radio label="6" size="large">其他</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="社会组织名称" prop="riskName" label-width="140">
            <el-select-v2
              v-model="form.riskName"
              :options="riskNameOptions"
              placeholder="请选择社会组织名称"
              class="select"
              filterable
              @change="change"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="风险类别" prop="riskType">
            <el-radio-group v-model="form.riskType">
              <!--              <el-radio-->
              <!--                v-for="it in riskTypeOptions"-->
              <!--                :label="it.value"-->
              <!--                size="large"-->
              <!--                >{{ it.label }}</el-radio-->
              <!--              >-->
              <el-select-v2
                v-model="form.riskType"
                :options="riskTypeOptions"
                placeholder="请选择风险类别"
                class="select"
                filterable
                clearable
                @change="change"
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="是否转入协同治理" prop="state" label-width="140">
            <el-radio-group v-model="form.state">
              <el-radio label="2" size="large">是</el-radio>
              <el-radio label="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="佐证材料" prop="files">
            <MBackingMaterial
              v-model="form.files"
              dateFormat="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="风险详情" prop="riskDetail">
            <el-input
              v-model="form.riskDetail"
              input-style="height: 200px"
              :rows="2"
              type="textarea"
              placeholder="请输入风险详情"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="整改要求" prop="rect">
            <el-input
              v-model="form.rect"
              input-style="height: 200px"
              :rows="2"
              type="textarea"
              placeholder="请输入整改要求"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="btns">
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="submitForm()" v-loading="loading">
        确定
      </el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {
  getManagerChild,
  riskAddOrUpd,
  riskDetail,
  soptCheckAdd,
  soptCheckUpd,
  sorgList
} from '@/api/spotCheck/spotCheck'
import {
  dialogFields,
  fields
} from '@/views/spotCheck/spotCheck/problemEntry/config'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { dateFormat } from '@/utils'

const router = useRouter()
const route = useRoute()
const formVisible = ref(false)
const riskNameOptions = ref([])
const riskTypeOptions = ref([])
// 0 民办非企业 riskMingBan 1 社会团体 riskSheTuan
const riskTypeOptionsObj = ref({
  riskMingBan: [],
  riskSheTuan: []
})

const emit = defineEmits(['reload'])

onMounted(async () => {
  let res = await sorgList()
  riskNameOptions.value = res.data.map((i) => ({
    value: i.orgName,
    label: i.orgName,
    labelId: i.sorgInfoId,
    types: i.types
  }))

  const riskMingBan = await getManagerChild('riskMingBan')
  riskTypeOptionsObj.value.riskMingBan = riskMingBan.data.map((i) => ({
    value: i.name,
    label: i.name,
    riskLevel: i.relationParameterName
  }))

  const riskSheTuan = await getManagerChild('riskSheTuan')
  riskTypeOptionsObj.value.riskSheTuan = riskSheTuan.data.map((i) => ({
    value: i.name,
    label: i.name,
    riskLevel: i.relationParameterName
  }))

  //详情
  if (route.query?.id) {
    riskDetail({ sorgRiskId: route.query.id }).then((res) => {
      if (Array.isArray(res.data.file) && res.data.file.length > 0) {
        form.files = res.data.file.map((i) => ({
          fileSum: i.filePage,
          isSave: true,
          name: i.fileName,
          createdAt: dateFormat(i.createTime, 'YYYY-MM-DD'),
          time: i.createTime,
          timestamp: i.createTime,
          isAdd: true,
          file: [
            {
              name: i.fileName,
              status: 'success',
              url: i.fileUrl
            }
          ]
        }))
      } else {
        form.files = []
      }
      form.source = res.data.source.toString()
      form.riskName = res.data.riskName
      form.riskType = res.data.riskType
      form.state = res.data.state.toString()
      form.riskDetail = res.data.riskDetail
      form.rect = res.data.rect
      form.sorgRiskId = route.query.id
      //change(res.data.riskType)
      console.log('riskTypeOptionsObj', riskTypeOptionsObj.value.riskMingBan)

      if (
        riskNameOptions.value.find((i) => i.value === res.data.riskName)
          .types === 0
      ) {
        riskTypeOptions.value = riskTypeOptionsObj.value.riskMingBan
      } else {
        riskTypeOptions.value = riskTypeOptionsObj.value.riskSheTuan
      }
    })
  }
  //问题类型
  // getManagerChild('theTypeOfProblemRisk').then((res) => {
  //   riskTypeOptions.value = res.data.map((i) => ({
  //     value: i.name,
  //     label: i.name,
  //     riskLevel: i.relationParameterName
  //   }))
  // })
  //问题类型
})

const change = (e) => {
  console.log('e=>', e, riskTypeOptionsObj.value)
  let arr = []
  if (riskNameOptions.value.some((i) => i.value == e)) {
    let type = riskNameOptions.value.find((i) => i.value === e).types
    console.log('type=>',type)
    if (type === 0) {
      riskTypeOptions.value = riskTypeOptionsObj.value.riskMingBan
    } else {
      riskTypeOptions.value = riskTypeOptionsObj.value.riskSheTuan
    }
  }
}
//新增
const form = reactive({
  files: [],
  source: undefined,
  riskName: undefined,
  riskType: [],
  state: '0',
  riskDetail: undefined,
  rect: undefined
})

const rules = ref({
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  riskName: [{ required: true, message: '请选择', trigger: 'blur' }],
  source: [{ required: true, message: '请选择', trigger: 'blur' }],
  riskType: [{ required: true, message: '请选择', trigger: 'blur' }],
  state: [{ required: true, message: '请选择', trigger: 'blur' }],
  riskDetail: [{ required: true, message: '请选择', trigger: 'blur' }]
})

const PersonnelSelectionRef = ref(false)
//抽检人员
const open = () => {
  PersonnelSelectionRef.value.show()
}

const loading = ref(false)
const ruleFormRef = ref()
const submitForm = () => {
  console.log('form', form)
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    let files = form.files
      .filter((i) => i.isSave)
      .map((i) => {
        let file = {
          fileName: i.name,
          filePage: i.fileSum,
          fileUrl: '',
          createTime: i?.isAdd ? i.time : i.timestamp
        }
        if (Array.isArray(i.file) && i.file.length > 0) {
          //上传了文件
          file.fileName = i.name
          file.fileUrl = i.file[0].url
        }
        return file
      })
    let riskLevel = ''
    try {
      riskLevel = riskTypeOptions.value.find(
        (i) => form.riskType === i.value
      ).riskLevel
    } catch (e) {}

    let riskId = riskNameOptions.value.find(
      (i) => i.label === form.riskName
    ).labelId

    let data = {
      ...form,
      files,
      riskLevel,
      riskId
    }
    loading.value = true
    riskAddOrUpd(data)
      .then((res) => {
        ElMessage.success(form.sorgRiskId ? '编辑成功' : '提交成功')
        back()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 取消
function cancel() {
  ElMessageBox.confirm('确定进行取消操作？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      back()
    })
    .catch(() => {})
}

const back = () => {
  router.go(-1)
}
</script>

<style scoped lang="scss">
.search {
  display: flex;
  justify-content: space-between;
}
.btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 20px 0;
  border-top: 1px solid #e9e9e9;
}
.select {
  width: 480px;
}
:deep(.el-card__body) {
  padding: 20px 0;
}
</style>
